package service

import (
	"database-platform/dal/db"
	"database-platform/logger"
	"database-platform/model"
	"fmt"
)

// GetAccountList 获取账号列表
func GetAccountList(params *model.AccountListRequest) (*model.AccountListResponse, error) {
	var response = &model.AccountListResponse{}

	var request = &model.Account{
		Username:   params.Username,
		UserType:   params.UserType,
		ClusterID:  params.ClusterID,
		DatabaseID: params.DatabaseID,
		DBType:     params.DBType,
	}

	result, count, err := db.ListAccountRecords(request, params.Page, params.PageSize, params.Search, params.ShowCluster, params.ShowDatabase)
	if err != nil {
		return nil, err
	}
	msg := fmt.Sprintf("[service.GetAccountList], result: %v, count:%d, request: %v", result, count, request)
	logger.Logger.Warn(msg)

	response.Count = count
	response.Records = result
	response.Page = params.Page
	response.PageSize = params.PageSize

	return response, nil
}

func GetAccountById(id int) (*model.Account, error) {
	result, err := db.GetAccountRecordById(id)
	if err != nil {
		return nil, err
	}
	msg := fmt.Sprintf("[service.GetAccountById], result: %v,  id: %v", result, id)
	logger.Logger.Warn(msg)

	return result, nil
}

// InsertAccount 插入账号记录
func InsertAccount(account *model.Account) error {
	err := db.InsertAccountRecord(account)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.InsertAccount],  account: %v", account)
	logger.Logger.Warn(msg)

	return nil
}

// UpdateAccount 更新账号记录
func UpdateAccount(id int, account *model.Account) error {
	err := db.UpdateAccountRecord(id, account)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.UpdateAccount],  account: %v", account)
	logger.Logger.Warn(msg)

	return nil
}

// DeleteAccount 删除账号记录
func DeleteAccount(id int) error {
	err := db.DeleteAccountRecord(id)
	if err != nil {
		return err
	}

	msg := fmt.Sprintf("[service.DeleteAccount],  id: %v", id)
	logger.Logger.Warn(msg)

	return nil
}
